package info.harmonyshive.imagepicker;

import com.yalantis.ucrop.util.LogUtils;
import com.yalantis.ucrop.view.GestureCropImageView;
import com.yalantis.ucrop.view.UCropView;
import info.harmonyshive.imagepicker.slice.MainAbilitySlice;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.data.rdb.ValuesBucket;
import ohos.global.icu.text.DecimalFormat;
import ohos.media.image.ImagePacker;
import ohos.media.image.PixelMap;
import ohos.media.image.common.Size;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;

import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class BasicAbility extends AbilitySlice {
  /*  public static Intent createIntent(Uri uri) {
        Intent intent = new Intent();
        intent.setParam("uri", uri);
        Operation operation = new Intent.OperationBuilder()
                .withBundleName("info.harmonyshive.ucroptest")
                .withAbilityName("info.harmonyshive.ucroptest.CropPicture")
                .build();
        intent.setOperation(operation);
        return intent;
    }
*/
    //总布局
    private DirectionalLayout directionalLayout = new DirectionalLayout(this);
    private DirectionalLayout.LayoutConfig layoutConfig = new DirectionalLayout.LayoutConfig(ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_PARENT);
    //缩放和旋转控件布局
    private DirectionalLayout rotationController = new DirectionalLayout(this);
    private DirectionalLayout.LayoutConfig rotationConfig = new DirectionalLayout.LayoutConfig(ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_CONTENT);
    private DirectionalLayout scaleController = new DirectionalLayout(this);
    private DirectionalLayout.LayoutConfig scaleConfig = new DirectionalLayout.LayoutConfig(ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_CONTENT);
    //uCrop
    private UCropView uCropView;
    private GestureCropImageView mGestureCropImageView;
    //缩放和旋转参数
    private float mDegree;
    private float mFactor;
    private Text text;
    private Text text2;
    private DecimalFormat df = new DecimalFormat("#.00");

    //待裁剪图片的URI
    public Uri uri_i;
   public     PixelMap pixelmap;


    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        //URI_IN
//        uri_i =  intent.getSequenceableParam("uri");
        uri_i=intent.getUri();
        //URI_OUT
        String filename = "test.jpg";
        PixelMap.InitializationOptions options = new PixelMap.InitializationOptions();
        options.size = new Size(100,100);
        pixelmap= PixelMap.create(options);
        Uri uri_o = saveImage(filename, pixelmap);
        LogUtils.LogInfo("UcropView init", "true");
        //UcropView
        uCropView = new UCropView(this);
        try {
            uCropView.getCropImageView().setImageUri(uri_i, uri_o);
            LogUtils.LogInfo("qqqqqqqq:", "ImageUri set true");
            uCropView.getOverlayView().setShowCropFrame(true);
            uCropView.getOverlayView().setShowCropGrid(true);
            uCropView.getOverlayView().setDimmedColor(Color.TRANSPARENT.getValue());

        } catch (Exception e) {
            e.printStackTrace();
        }
        //全局背景
        ShapeElement background = new ShapeElement();
        background.setRgbColor(new RgbColor(Color.LTGRAY.getValue()));
        //Button背景
        ShapeElement buttonBackground = new ShapeElement();
        buttonBackground.setRgbColor(new RgbColor(Color.CYAN.getValue()));
        buttonBackground.setCornerRadius(50f);
        //裁剪Button
        Button button = new Button(this);
        button.setText("裁剪");
        button.setTextSize(100);
        button.setMarginTop(50);
        button.setPadding(50,50,50,50);
        button.setBackground(buttonBackground);
        button.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Intent intent1 = new Intent();
                Uri uri = cropAndSaveImage();
                intent1.setUri(uri);
                intent1.setParam("uri", intent1.getUri());
                present(new MainAbilitySlice(),intent1);
            }
        });

        //旋转+90Button
        Button button_plus_90 = new Button(this);
        button_plus_90.setText("+90°");
        button_plus_90.setTextSize(80);
        button_plus_90.setBackground(buttonBackground);
        button_plus_90.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                float degrees = 90f;
                //计算旋转中心
                float center_X = uCropView.getOverlayView().getCropViewRect().getCenter().getPointX();
                float center_Y = uCropView.getOverlayView().getCropViewRect().getCenter().getPointY();
                //旋转
                uCropView.getCropImageView().postRotate(degrees,center_X,center_Y);
                //适配
                uCropView.getCropImageView().setImageToWrapCropBounds(false);
                //显示旋转角度
                mDegree = uCropView.getCropImageView().getCurrentAngle();
                text.setText("当前旋转角度: " + df.format(mDegree) + " °");
            }
        });
        //旋转-90Button
        Button button_minus_90 = new Button(this);
        button_minus_90.setText("-90°");
        button_minus_90.setTextSize(80);
        button_minus_90.setBackground(buttonBackground);
        button_minus_90.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                float degrees = -90f;
                //计算旋转中心
                float center_X = uCropView.getOverlayView().getCropViewRect().getCenter().getPointX();
                float center_Y = uCropView.getOverlayView().getCropViewRect().getCenter().getPointY();
                //旋转
                uCropView.getCropImageView().postRotate(degrees,center_X,center_Y);
                //适配
                uCropView.getCropImageView().setImageToWrapCropBounds(false);
                //显示旋转角度
                mDegree = uCropView.getCropImageView().getCurrentAngle();
                text.setText("当前旋转角度: " + df.format(mDegree) + " °");
            }
        });


        //Slider背景
        ShapeElement sliderBackground = new ShapeElement();
        sliderBackground.setRgbColor(new RgbColor(Color.BLUE.getValue()));
        //旋转Slider
        Slider slider_rotation = new Slider(this);
        slider_rotation.setWidth(800);
        slider_rotation.setProgressValue(50);
        slider_rotation.setProgressColor(Color.BLUE);
        slider_rotation.setProgressBackgroundElement(sliderBackground);
        slider_rotation.setValueChangedListener(new Slider.ValueChangedListener() {
            @Override
            public void onProgressUpdated(Slider slider, int i, boolean b) {
                float degrees = i - 50f;
                //计算旋转中心
                float center_X = uCropView.getOverlayView().getCropViewRect().getCenter().getPointX();
                float center_Y = uCropView.getOverlayView().getCropViewRect().getCenter().getPointY();
                //旋转
                uCropView.getCropImageView().postRotate(0.05f * degrees,center_X,center_Y);
                //显示旋转角度
                mDegree = uCropView.getCropImageView().getCurrentAngle();
                text.setText("当前旋转角度: " + df.format(mDegree) + " °");
            }

            @Override
            public void onTouchStart(Slider slider) {

            }

            @Override
            public void onTouchEnd(Slider slider) {
                uCropView.getCropImageView().setImageToWrapCropBounds(false);
                slider.setProgressValue(50);
                //自适应后的缩放倍数
                mFactor = uCropView.getCropImageView().getCurrentScale();
                text2.setText("当前缩放倍数: x" + df.format(mFactor));
            }
        });
//        rotationConfig.alignment = LayoutAlignment.HORIZONTAL_CENTER;
        rotationController.setAlignment(LayoutAlignment.HORIZONTAL_CENTER);
        rotationController.setLayoutConfig(rotationConfig);
        rotationController.setOrientation(Component.HORIZONTAL);
        rotationController.addComponent(button_minus_90);
        rotationController.addComponent(slider_rotation);
        rotationController.addComponent(button_plus_90);




        //缩放x2Button
        Button button_plus_2 = new Button(this);
        button_plus_2.setText("x2");
        button_plus_2.setTextSize(80);
        button_plus_2.setBackground(buttonBackground);
        button_plus_2.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                float factor = 2f;
                //计算旋转中心
                float center_X = uCropView.getOverlayView().getCropViewRect().getCenter().getPointX();
                float center_Y = uCropView.getOverlayView().getCropViewRect().getCenter().getPointY();
                //旋转
                uCropView.getCropImageView().postScale(factor,center_X,center_Y);
                //适配
                uCropView.getCropImageView().setImageToWrapCropBounds(false);
                //显示缩放倍数
                mFactor = uCropView.getCropImageView().getCurrentScale();
                text2.setText("当前缩放倍数: x" + df.format(mFactor));
            }
        });

        //缩放/2Button
        Button button_minus_2 = new Button(this);
        button_minus_2.setText("/2");
        button_minus_2.setTextSize(80);
        button_minus_2.setBackground(buttonBackground);
        button_minus_2.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                float factor = 0.5f;
                //计算旋转中心
                float center_X = uCropView.getOverlayView().getCropViewRect().getCenter().getPointX();
                float center_Y = uCropView.getOverlayView().getCropViewRect().getCenter().getPointY();
                //旋转
                uCropView.getCropImageView().postScale(factor,center_X,center_Y);
                //适配
                uCropView.getCropImageView().setImageToWrapCropBounds(false);
                //显示缩放倍数
                mFactor = uCropView.getCropImageView().getCurrentScale();
                text2.setText("当前缩放倍数: x" + df.format(mFactor));
            }
        });

        //缩放Slider
        Slider slider_Scale = new Slider(this);
        slider_Scale.setWidth(800);
        slider_Scale.setProgressValue(50);
        slider_Scale.setProgressColor(Color.BLUE);
        slider_Scale.setProgressBackgroundElement(sliderBackground);
        slider_Scale.setValueChangedListener(new Slider.ValueChangedListener() {
            @Override
            public void onProgressUpdated(Slider slider, int i, boolean b) {
                float factor = i - 50f;
                //计算旋转中心
                float center_X = uCropView.getOverlayView().getCropViewRect().getCenter().getPointX();
                float center_Y = uCropView.getOverlayView().getCropViewRect().getCenter().getPointY();
                //旋转
                uCropView.getCropImageView().postScale((float) Math.exp(0.001f * factor),center_X,center_Y);
                //显示缩放倍数
                mFactor = uCropView.getCropImageView().getCurrentScale();
                text2.setText("当前缩放倍数: x" + df.format(mFactor));
            }

            @Override
            public void onTouchStart(Slider slider) {

            }

            @Override
            public void onTouchEnd(Slider slider) {
                uCropView.getCropImageView().setImageToWrapCropBounds(false);
                slider.setProgressValue(50);
                //自适应后的缩放倍数
                mFactor = uCropView.getCropImageView().getCurrentScale();
                text2.setText("当前缩放倍数: x" + df.format(mFactor));

            }
        });
//        scaleConfig.alignment = LayoutAlignment.HORIZONTAL_CENTER;
        scaleController.setAlignment(LayoutAlignment.HORIZONTAL_CENTER);
        scaleController.setLayoutConfig(scaleConfig);
        scaleController.setOrientation(Component.HORIZONTAL);
        scaleController.addComponent(button_minus_2);
        scaleController.addComponent(slider_Scale);
        scaleController.addComponent(button_plus_2);

        //旋转Text
        text = new Text(this);
        text.setText("当前旋转角度: " + df.format(mDegree) + " °");
        text.setTextSize(50);

        //缩放Text
        text2 = new Text(this);
        text2.setText("当前缩放倍数: x" + df.format(mFactor));
        text2.setTextSize(50);


        directionalLayout.setBackground(background);
        directionalLayout.setAlignment(LayoutAlignment.HORIZONTAL_CENTER);
        directionalLayout.setLayoutConfig(layoutConfig);
        directionalLayout.addComponent(uCropView);
        directionalLayout.addComponent(rotationController);
        directionalLayout.addComponent(text);
        directionalLayout.addComponent(scaleController);
        directionalLayout.addComponent(text2);
        //裁剪按钮
        directionalLayout.addComponent(button);
        setUIContent(directionalLayout);


    }

    protected Uri cropAndSaveImage() {
        Uri uri=null;
        mGestureCropImageView = uCropView.getCropImageView();
        mGestureCropImageView.cropAndSaveImage("image/jpg", 90,null);
        String imageOutputPath = mGestureCropImageView.getImageOutputPath();

       Intent intent=new Intent();
        int begin = imageOutputPath.indexOf("media");
        int last = imageOutputPath.length();
        String substring = imageOutputPath.substring(begin, last);
        String abilityPath = "dataability:///" + substring;
        intent.setUri(Uri.parse(abilityPath));
        uri=intent.getUri();

        return  uri;

    }



    private Uri saveImage(String fileName, PixelMap pixelMap) {
        try {
            ValuesBucket valuesBucket = new ValuesBucket();
            valuesBucket.putString(AVStorage.Images.Media.DISPLAY_NAME, fileName);
            valuesBucket.putString("relative_path", "DCIM/");
            valuesBucket.putString(AVStorage.Images.Media.MIME_TYPE, "image/JPEG");
            //应用独占
            valuesBucket.putInteger("is_pending", 1);
            DataAbilityHelper helper = DataAbilityHelper.creator(this);
            int id = helper.insert(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, valuesBucket);
            Uri uri = Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, String.valueOf(id));
            //这里需要"w"写权限
            FileDescriptor fd = helper.openFile(uri, "w");
            ImagePacker imagePacker = ImagePacker.create();
            ImagePacker.PackingOptions packingOptions = new ImagePacker.PackingOptions();
            OutputStream outputStream = new FileOutputStream(fd);

            packingOptions.format = "image/jpeg";
            packingOptions.quality = 90;
            boolean result = imagePacker.initializePacking(outputStream, packingOptions);
            if (result) {
                result = imagePacker.addImage(pixelMap);
                if (result) {
                    long dataSize = imagePacker.finalizePacking();
                }
            }
            outputStream.flush();
            outputStream.close();
            valuesBucket.clear();
            //解除独占
            valuesBucket.putInteger("is_pending", 0);
            helper.update(uri, valuesBucket, null);
            return uri;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }




    public void startResultActivity(Uri uri) {
        Intent intent = new Intent();
        intent.setParam("uri", uri);


//        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withBundleName("info.harmonyshive.ucroptest")
                .withAbilityName("info.harmonyshive.ucroptest.MainAbility")
                .build();
        intent.setOperation(operation);
        startAbility(intent);

//        setResult(0, intent);
//        terminateAbility();
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
